<?php

namespace mybackend\controllers\official;

use Yii;
use yii\data\Pagination;
use mybackend\controllers\BaseController;
use common\services\official\ArticleService;
use common\models\official\ArticleModel;
use common\error\ErrorCode;
use common\support\CacheManage;
use common\entities\official\ArticleEntity;
use common\entities\official\DirEntity;
use common\entities\myhtsq\ActionCode;
use common\support\QRSupport;
use yii\helpers\Html;

class ArticleController extends BaseController {


    
    public $_articleService;
    public $layout = '@app/views/official/layouts/main.php';
    
    public function __construct($id, $module, ArticleService $ArticleService, $config = []) {
        $this->_articleService = $ArticleService;
        parent::__construct($id, $module, $config);
    }

    protected function roleAuthRules() {
        return [
            'actions' => ['Delete', 'Edit', 'GetList', 'QuickSet', 'Release', 'Save'],
            'rules' => [
                [
                    'allow' => true,
                    'actionCodeMaps' => [
                        'GetList' => ActionCode::OFFICIAL_ALL,
                        'Edit' => ActionCode::OFFICIAL_ALL,
                        'Delete' => ActionCode::OFFICIAL_ALL,
                        'QuickSet' => ActionCode::OFFICIAL_ALL,
                        'Release' => ActionCode::OFFICIAL_ALL,
                        'Save' => ActionCode::OFFICIAL_ALL,
                    ]
                ]
            ]
        ];
    }    
    
    
    /**
     * 保存文章
     */
    public function actionSave ($copy = 0) {
        $this->exitIfNotPost();
        $model = new ArticleModel(['scenario' => 'save']);
        if ($model->load(Yii::$app->request->post(),'')) {
            if(!$model->validate()) {
                return $this->json(array(
                    "retCode"=>ErrorCode::ERR_CMS_ARTICLE_EMPTY,
                    "retMsg"=>join("\n", $model->getFirstErrors())
                ));
            }
            $result = $this->_articleService->saveArticle($model);
            if ($copy != 0) {
                $model->aId = 0;
                $result = $this->_articleService->saveArticle($model);
            }
            $this->exportJson($result, $this->_articleService->getErrCode(), $this->_articleService->getErrMsg());
        } else {
            $this->errorParam();
        }     
    }

    /**
     * 更新pv
     * @param type $articleId
     */
    public function actionUpdatePv ($aId) {
        $this->exitIfNotPost();
        $this->_articleService->updatePv($aId);
    }

    /**
     * 编辑页
     * @param type $aId
     */
    public function actionEdit () {
        $dirModel = new DirEntity();
        $aId = $this->getParam("id");
        $result = $this->_articleService->getArticleInfo($aId);
        $result['model'] = $dirModel;
        return $this->render('edit', $result);
    }
        
    public function actionGetList () {
        $data = array();
        if ($this->isAjaxRequest()) {
            if (Yii::$app->request->get('update')) {
                $section  = Yii::$app->request->get('update');
                $value = Yii::$app->request->get('value');
                $ids = Yii::$app->request->get('ids');
                if ( ! empty($section) && ! empty($ids)) {
                    $this->_articleService->updateBatch($section, $value, $ids); // 批量修改
                }
            }
            $page = Yii::$app->request->get('page', 1);
            $page_size = Yii::$app->request->get('rows', 20);
            $sidx = Yii::$app->request->get('sidx', 'id');
            $sord = Yii::$app->request->get('sord', 'DESC');   
            $search = Yii::$app->request->get('keyword');   
            $sidx = $this->_articleService->dealField($sidx);

            $count = ArticleEntity::find();
            if ( ! empty($search)) {
                $count = $count->where(['like', 'title', $search])->orwhere(['like', 'tag', $search]);
            }
            $pages = new Pagination(['totalCount' => $count->andwhere(['del' => 0])->count()]);
            $pages->setPageSize($page_size, true);            

            $result = $this->_articleService->getArticleAllList($sidx, $sord, $page, $page_size, $search);
            foreach ($result as $key => $item) {
                $data['records'] = $pages->totalCount;
                $data['total'] = ceil($pages->totalCount / $page_size);
                $data['rows'][$key] = array(
                    'id' => $item->a_id,
                    'aId' => $item->a_id,
                    'title' => html_entity_decode($item->title),
                    'dirName' => $item->dir ? $item->dir->name : 'empty',
                    'tag' => html_entity_decode($item->tag),
                    //'share_num' => $item->share_num,
                    'sort' => $item->sort,
                    'status' => $item->status == 1 ? "已发布" : "未发布",
                    'modifiedBy' => $item->modified_by,
                    'createdBy' => $item->created_by,
                    'modifiedTime' => date('y-m-d H:i:s', $item->modified_time),
                    'edit' => '<button onclick="updateStatus('.$item->a_id.', 1, $(this), 1)">头版</button>  '
                    .'<button onclick="updateStatus('.$item->a_id.', 2, $(this), 1)">取消头版</button>  '
                    .'<button onclick="updateStatus('.$item->a_id.', 1, $(this), 2)">发布</button>  '
                    .'<button onclick="updateStatus('.$item->a_id.', 2, $(this), 2)">取消发布</button>',
                );
            }   
            echo json_encode($data);
            return Yii::$app->end();            
        }
        return $this->render('getList');
    }
    
    /**
     * 发布
     */
    public function actionRelease () {
        $aId = Yii::$app->request->post('id');
        $type = Yii::$app->request->post('type'); // 1发布，2取消发布
        if(empty($aId)){ 
            return Yii::$app->end();
        }
        $entity = ArticleEntity::find()->where(['a_id' => $aId])->one();
        $entity->status = ($type == 1 ? 1 : 0);
        $result = $entity->update();
        if ($result === false) {
            echo json_encode(['success' => 0]);
        } else {
            echo json_encode(['success' => 1]);
        }        
    }
    
    /**
     * 快速修改
     * @return type
     */
    public function actionQuickSet() {
        $id = $_POST['id'];
        unset($_POST['id']);
        unset($_POST['oper']);
        $model = ArticleEntity::find()->where(['a_id' => $id])->one();
        $model->modified_by = \Yii::$app->user->identity->username;
        $model->modified_time = time();
        if (!$model) {
            echo json_encode(['status' => false, 'errMsg' => \common\error\ErrorMsg::getDefaultMsg()]);
            return Yii::$app->end();
        }
        $model->setAttributes($_POST);
        $content = '';
        if (!$model->save()) {
            foreach ($model->getErrors() as $errors) {
                foreach ($errors as $error) {
                    if ($error != '')
                        $content.="{$error}";
                }
            }
            echo json_encode(['status' => false, 'errMsg' => $error]);
            return Yii::$app->end();
        }
    }
    
    /**
     * 删除
     */
    public function actionDelete () {
        $aId = Yii::$app->request->post('id');
        if(empty($aId)){ 
            echo json_encode(['success' => 0]);
        }
        $entity = ArticleEntity::find()->where(['a_id' => $aId])->one();
        $entity->del = 1;
        $result = $entity->update();
        if ($result === false) {
            echo json_encode(['success' => 0]);
        } else {
            echo json_encode(['success' => 1]);
        }         
    }
    
    /**
     * 二维码
     * @param type $url
     */
    public function actionImageurl($id){
        $url = "http://".$_SERVER['HTTP_HOST']."/details.html?articalId=".$id;
        //$url = urlencode($url);
        QRSupport::responseQR($url,240);
    }    
     
}
